import { login, getUserInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { constantRoutes, resetRouter } from '@/router'
// 获取默认状态数据
const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: {},
    routes: constantRoutes
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_ROUTES: (state, newRoutes) => {
    state.routes = [...constantRoutes, ...newRoutes]
  }
}

const actions = {
  // 用户登录
  login({ commit }, data) {
    return new Promise((resolve, reject) => {
      login(data)
        .then((res) => {
        // 把token存在store
          commit('SET_TOKEN', res)
          // 把token存在浏览器
          setToken(res)
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  // 获取用户信息
  getInfo({ commit }) {
    return new Promise((resolve, reject) => {
      getUserInfo().then((res) => {
        commit('SET_USER_INFO', res)
        resolve(res)
      })
    })
  },
  // 退出登录
  logout({ commit }) {
    return new Promise((resolve, reject) => {
      removeToken() // must remove  token  first
      commit('RESET_STATE') // reset vuex status
      resetRouter()
      resolve()
    })
  },
  // 删除token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE') // reset vuex status
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
